﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DunSilverlight.Web.Comm;
using DunLibrary.Dun;
using System.ServiceModel.Activation;
using NHibernate;
using System.Data;

namespace DunSilverlight.Web.DunWcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“CaseService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class CaseService :BaseService<Case>, ICaseService
    {
        public string AllotCase(string jsonCaseIds, int operId)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    IDbConnection cnn = sess.Connection;

                    IList<int> ids = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(jsonCaseIds);

                    string strIds = null;

                    foreach (int id in ids)
                    {
                        strIds += strIds == null ? id.ToString() : "," + id;
                    }

                    string sql = string.Format("update Dun_Case set OperId ={0} where Id in ({1})", operId, strIds);

                    IDbCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = sql;
                    int result = cmd.ExecuteNonQuery();

                    return PackJsonResult("true", result.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    return PackJsonResult("false","0", ex.Message);
                }

            }
        }


        /// <summary>
        /// 将满足条件的记录分配给选定的操作员
        /// 规则：
        /// 如将9个case分配给3个操作员
        /// 首先将case按金额排序，进行如下分配
        /// 操作员1：1 6 7
        /// 操作员2：2 5 8
        /// 操作员3：3 4 9
        /// </summary>
        /// <param name="hql"></param>
        /// <param name="operIds"></param>
        /// <returns></returns>
        public string QuickAllocCase(string hql, string operIdsStr)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    //得到按金额排序后的case id
                    IList<int> ls = sess.CreateQuery(hql).List<int>();

                    IList<int> operIds = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(operIdsStr);
                    
                    //case数量
                    int numOfCase = ls.Count;
                    //操作员数量
                    int numOfOper = operIds.Count;

                    //任务分配list
                    List<List<int>> task = new List<List<int>>();
                    //初始化
                    for (int iOper = 0; iOper < numOfOper; iOper++)
                    {
                        task.Add(new List<int>());
                    }

                    bool flag = true;
                    int i = 0;

                    //先分配ls中能整除到numOfOper的case
                    int alignNumOfCase = numOfCase / numOfOper * numOfOper;
                    for (; i < alignNumOfCase; i += numOfOper)
                    {
                        for (int j = 0; j < numOfOper; j++)
                        {
                            task[j].Add(flag ? ls[i + j] : ls[i + numOfOper - 1 - j]);
                        }
                        flag = !flag;
                    }
                    //分配ls中剩下的case
                    for (int j = 0; i < numOfCase; i++, j++)
                    {
                        task[j].Add(ls[i]);
                    }

                    IDbConnection cnn = sess.Connection;
                    StringBuilder sb = new StringBuilder();
                    for (i = 0; i < numOfOper; i++)
                    {
                        sb.AppendFormat("update Dun_Case set OperId ={0} where Id in ({1});", 
                            operIds[i], string.Join(",",task[i]));
                    }
                    

                    IDbCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = sb.ToString();
                    int result = cmd.ExecuteNonQuery();

                    return PackJsonResult("true", result.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }

        /// <summary>
        /// 为指定case分配
        /// </summary>
        /// <param name="caseIdsStr"></param>
        /// <param name="operIdsStr"></param>
        /// <returns></returns>
        public string QuickAllocCaseWithCaseIds(string caseIdsStr, string operIdsStr)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    //得到按金额排序后的case id
                    IList<int> ls = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(caseIdsStr);

                    IList<int> operIds = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(operIdsStr);

                    //case数量
                    int numOfCase = ls.Count;
                    //操作员数量
                    int numOfOper = operIds.Count;

                    //任务分配list
                    List<List<int>> task = new List<List<int>>();
                    //初始化
                    for (int iOper = 0; iOper < numOfOper; iOper++)
                    {
                        task.Add(new List<int>());
                    }

                    bool flag = true;
                    int i = 0;

                    //先分配ls中能整除到numOfOper的case
                    int alignNumOfCase = numOfCase / numOfOper * numOfOper;
                    for (; i < alignNumOfCase; i += numOfOper)
                    {
                        for (int j = 0; j < numOfOper; j++)
                        {
                            task[j].Add(flag ? ls[i + j] : ls[i + numOfOper - 1 - j]);
                        }
                        flag = !flag;
                    }
                    //分配ls中剩下的case
                    for (int j = 0; i < numOfCase; i++, j++)
                    {
                        task[j].Add(ls[i]);
                    }

                    IDbConnection cnn = sess.Connection;
                    StringBuilder sb = new StringBuilder();
                    for (i = 0; i < numOfOper; i++)
                    {
                        sb.AppendFormat("update Dun_Case set OperId ={0} where Id in ({1});",
                            operIds[i], string.Join(",", task[i]));
                    }


                    IDbCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = sb.ToString();
                    int result = cmd.ExecuteNonQuery();

                    return PackJsonResult("true", result.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }


        public string UndoCaseAlloc(string hql)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    //得到case id
                    IList<int> ls = sess.CreateQuery(hql).List<int>();

                    IDbConnection cnn = sess.Connection;
                    string sql = string.Format("update Dun_Case set OperId = null where OperId is not null and Id in ({0});",
                        string.Join(",", ls));


                    IDbCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = sql;
                    int result = cmd.ExecuteNonQuery();

                    return PackJsonResult("true", result.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }

        public string UndoCaseAllocWithCaseIds(string caseIdsStr)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    //得到case id
                    IList<int> ls = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<int>>(caseIdsStr);

                    IDbConnection cnn = sess.Connection;
                    string sql = string.Format("update Dun_Case set OperId = null where OperId is not null and Id in ({0});",
                        string.Join(",", ls));


                    IDbCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = sql;
                    int result = cmd.ExecuteNonQuery();

                    return PackJsonResult("true", result.ToString(), string.Empty);
                }
                catch (Exception ex)
                {
                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }
    }
}
